package yuan.zk.config_center;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.proto.WatcherEvent;
import yuan.zk.node.ZKCreate;
import yuan.zk.watcher.ZKConnectionWatcher;

import java.util.concurrent.CountDownLatch;

/**
 * @version: 1.0
 * @Description: TODO
 * @author: zZmH
 * @date: 2020/09/11 18:33
 */


public class MyConfigCenter implements Watcher{
    static CountDownLatch latch = new CountDownLatch(1);
    static ZooKeeper zooKeeper;
    public static final String ip = "192.168.190.128:2181";
    public static final int TIME_OUT = 5000;
    private String url;
    private String username;
    private String password;


    @Override
    public void process(WatchedEvent event) {
        try {
            if (event.getType() == Watcher.Event.EventType.None) {
                if (event.getState() == Watcher.Event.KeeperState.SyncConnected) {
                    System.out.println("connected successfully!");
                    latch.countDown();
                } else if (event.getState() == Watcher.Event.KeeperState.Disconnected) {
                    System.out.println("shutdown the connection!");

                } else if (event.getState() == Watcher.Event.KeeperState.Expired) {
                    System.out.println("session timeout!");
                    zooKeeper = new ZooKeeper(ZKCreate.ip, ZKCreate.TIME_OUT,
                            new ZKConnectionWatcher());
                } else if (event.getState() == Watcher.Event.KeeperState.AuthFailed) {
                    System.out.println("authentication failure!");

                }
            } else if (event.getType() == Event.EventType.NodeDataChanged) {
                initValue();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    private void initValue() {
        try {
            zooKeeper = new ZooKeeper(ip, TIME_OUT, this);
            latch.await();
            this.url = new String(zooKeeper.getData("/config/url",
                    true,
                    null));
            this.username= new String(zooKeeper.getData("/config/username",
                    true,
                    null));
            this.password = new String(zooKeeper.getData("/config/password",
                    true,
                    null));

        } catch (Exception e) {
        }
    }

    public MyConfigCenter() {
        initValue();
    }

    public static void main(String[] args) throws InterruptedException {
        MyConfigCenter myConfigCenter = new MyConfigCenter();
        for (int i = 0; i < 20; i++) {
            Thread.sleep(5000);
            System.out.println("url: " + myConfigCenter.url);
            System.out.println("username: " + myConfigCenter.username);
            System.out.println("password: " + myConfigCenter.password);

        }



    }
}
